package com.lanbu.system.service.impl;

import java.security.SecureRandom;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.lanbu.common.config.KnowledgeProperties;
import com.lanbu.common.constant.DeptConstants;
import com.lanbu.common.constant.FastGptUserConstants;
import com.lanbu.common.core.domain.vo.FastGptOpenapiVo;
import com.lanbu.common.core.domain.vo.FastGptShareidVo;
import com.lanbu.common.utils.DateUtils;
import com.lanbu.system.domain.SysDeptOpenapi;
import com.lanbu.system.domain.SysDeptShareid;
import com.lanbu.system.domain.SysUserShareid;
import com.lanbu.system.domain.mongo.*;
import com.lanbu.system.mapper.*;
import com.lanbu.system.service.ISysUserService;
import com.lanbu.system.service.ISysUserShareidService;
import lombok.RequiredArgsConstructor;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.lanbu.common.annotation.DataScope;
import com.lanbu.common.constant.UserConstants;
import com.lanbu.common.core.domain.TreeSelect;
import com.lanbu.common.core.domain.entity.SysDept;
import com.lanbu.common.core.domain.entity.SysRole;
import com.lanbu.common.core.domain.entity.SysUser;
import com.lanbu.common.core.text.Convert;
import com.lanbu.common.exception.ServiceException;
import com.lanbu.common.utils.SecurityUtils;
import com.lanbu.common.utils.StringUtils;
import com.lanbu.common.utils.spring.SpringUtils;
import com.lanbu.system.service.ISysDeptService;
import org.springframework.transaction.annotation.Transactional;



/**
 * 部门管理 服务实现
 *
 * @author lanbu
 */
@Service
@RequiredArgsConstructor
public class SysDeptServiceImpl implements ISysDeptService
{
    private final SysDeptMapper deptMapper;

    private final SysRoleMapper roleMapper;

    private final MongoUsersService mongoUsersService;

    private final MongoTeamMembersService mongoTeamMembersService;

    private final MongoOpenApisService mongoOpenApisService;

    private final KnowledgeProperties knowledgeProperties;

    private final SysDeptOpenapiMapper sysDeptOpenapiMapper;

    private final SysDeptShareidMapper sysDeptShareidMapper;

    @Autowired
    private    MongoTeamsService mongoTeamsService;
    private final   MongoTeamMembersGroupsService mongoTeamMembersGroupsService;

    private  final MongoOutlinksService mongoOutlinksService;
    @Autowired
    private MongoAppsRepository mongoAppsRepository;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysUserShareidService sysUserShareidService;

    @Value("${shareIdprefix}")
    private  String shareIdprefix ;
    @Value("${shareIdsuffix}")
    private  String shareIdsuffix;

    @Autowired
    private MongoChatsService mongoChatsService;

    @Autowired
    private MongoChatitemsService mongoChatitemsService;
    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> selectDeptList(SysDept dept)
    {
        return deptMapper.selectDeptList(dept);
    }

    @Override
    public List<SysDept> selectDeptVoList(SysDept dept) {
        List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);

        if (depts != null && !depts.isEmpty()) {
            // 批量查询所有 deptId 对应的 SysDeptShareid 和 SysDeptOpenapi
            Set<Long> deptIds = depts.stream().map(SysDept::getDeptId).collect(Collectors.toSet());

            // 查询所有的 SysDeptShareid
            Map<Long, SysDeptShareid> shareidMap = sysDeptShareidMapper.selectByDeptIds(new ArrayList<>(deptIds)).stream()
                    .collect(Collectors.toMap(SysDeptShareid::getDeptId, Function.identity()));

            // 查询所有的 SysDeptOpenapi

            // 处理部门信息，加入相应的 FastGptShareidVo 和 FastGptOpenapiVo
            depts = depts.stream().map(sysDept -> {
                // 设置 FastGptShareidVo
                SysDeptShareid deptShareid = shareidMap.get(sysDept.getDeptId());
                FastGptShareidVo fastGptShareidVo = new FastGptShareidVo();
                if (deptShareid != null) {
                    fastGptShareidVo.setId(sysDept.getDeptId());
                    fastGptShareidVo.setShareId(deptShareid.getShareid());
                    fastGptShareidVo.setName(deptShareid.getName());
                }
                FastGptOpenapiVo fastGptOpenapiVo = new FastGptOpenapiVo();
                sysDept.setFastGptShareidVo(fastGptShareidVo);
                sysDept.setFastGptOpenapiVo(fastGptOpenapiVo);


                return sysDept;
            }).collect(Collectors.toList());
        }

        return depts;
    }

    /**
     * 查询部门树结构信息
     *
     * @param dept 部门信息
     * @return 部门树信息集合
     */
    @Override
    public List<TreeSelect> selectDeptTreeList(SysDept dept)
    {
        List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);
        return buildDeptTreeSelect(depts);
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDept> buildDeptTree(List<SysDept> depts)
    {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<Long> tempList = depts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
        for (SysDept dept : depts)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId()))
            {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts)
    {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据角色ID查询部门树信息
     *
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<Long> selectDeptListByRoleId(Long roleId)
    {
        SysRole role = roleMapper.selectRoleById(roleId);
        return deptMapper.selectDeptListByRoleId(roleId, role.isDeptCheckStrictly());
    }

    /**
     * 根据部门ID查询信息
     *
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public SysDept selectDeptById(Long deptId)
    {
        return deptMapper.selectDeptById(deptId);
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenDeptById(Long deptId)
    {
        return deptMapper.selectNormalChildrenDeptById(deptId);
    }

    /**
     * 是否存在子节点
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(Long deptId)
    {
        int result = deptMapper.hasChildByDeptId(deptId);
        return result > 0;
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId)
    {
        int result = deptMapper.checkDeptExistUser(deptId);
        return result > 0;
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public boolean checkDeptNameUnique(SysDept dept)
    {
        Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        SysDept info = deptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId());
        if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验部门是否有数据权限
     *
     * @param deptId 部门id
     */
    @Override
    public void checkDeptDataScope(Long deptId)
    {
        if (!SysUser.isAdmin(SecurityUtils.getUserId()) && StringUtils.isNotNull(deptId))
        {
            SysDept dept = new SysDept();
            dept.setDeptId(deptId);
            List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);
            if (StringUtils.isEmpty(depts))
            {
                throw new ServiceException("没有权限访问部门数据！");
            }
        }
    }

    /**
     * 新增保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertDept(SysDept dept)
    {
        SysDept info = deptMapper.selectDeptById(dept.getParentId());
        // 如果父节点不为正常状态，且父节点不为 0,则不允许新增子节点
        if (!(Long.valueOf(0L).equals(dept.getParentId()) || UserConstants.DEPT_NORMAL.equals(info.getStatus())))
        {
            throw new ServiceException("部门停用，不允许新增");
        }
        String ancestors = "0";
        if(!Long.valueOf(0L).equals(dept.getParentId())){
            ancestors = info.getAncestors() + "," + dept.getParentId();
        }
       dept.setAncestors(ancestors);
//        //新增客服部门时，判断是否可以修改客服部门
//        //一级节点新增时不用判断是否为客服部门
//        if (Long.valueOf(0L).equals(dept.getParentId())){
//        } else if ("1".equals(dept.getIsService())){
//            SysDept sysDept = this.findServiceDepartmentDeptId(dept.getParentId());
//            if (sysDept!=null){
//                throw new ServiceException("已存在客服部门，不允许新增");
//            }
//        }

        int result = deptMapper.insertDept(dept);

        // 判断如果是一级节点,则构建与fastGpt的联系 -- 可考虑改为异步
       // buildFastGptUser(dept);
        // 构建部门与 openapi 的绑定
        buildDeptBindOpenapi(dept);
if (dept.getFastGptShareidVo().getShareId()!=null&&!"".equals(dept.getFastGptShareidVo().getShareId())){
    buildDeptBindShareIdUsers(dept);

}

        return result;
    }
    //查询客服部门
    private SysDept findServiceDepartmentDeptId(Long deptId) {
        Long id = this.findRootTreeId(deptId);
        List<SysDept> depts = deptMapper.selectAllChildrenDeptById(id);
        if (depts==null){
            return null;
        }
        SysDept dept = null;
        for (int i = 0; i < depts.size(); i++) {
            SysDept dept1 = depts.get(i);
            if ("1".equals(dept1.getIsService())) {
                dept = dept1;
            }
        }
        return dept;
    }


    /**
     * 构建部门与fastGpt的联系
     */
    private void buildFastGptUser(SysDept dept) {
        String ancestors = dept.getAncestors();
        List<String> splitByComma = StrUtil.split(ancestors, ",");
        if(ObjectUtil.isNotNull(splitByComma) && splitByComma.size() != DeptConstants.DEPT_UNION_FAST_GPT_DEEP){
            return;
        }
        // 创建用户与 fastGpt 相关联
        MongoUsers mongoUsers = new MongoUsers();
        mongoUsers.setUsername(dept.getDeptId() + DeptConstants.DEPT_UNIQUE_SUFFIX_STR);
        mongoUsers.setPassword(SecureUtil.sha256(SecureUtil.sha256(dept.getDeptId() + DeptConstants.DEPT_UNIQUE_SUFFIX_STR)));
        mongoUsers.setStatus(FastGptUserConstants.USER_STATUS);
        //mongoUsers.setAvatar(FastGptUserConstants.USER_AVATAR);
        mongoUsers.setPromotionRate(FastGptUserConstants.USER_PROMOTION_RATE_COMMON);
        mongoUsers.setTimezone(FastGptUserConstants.TIME_ZONE);
        mongoUsers.setCreateTime(DateUtils.getNowDate());
        mongoUsers.setVersion(FastGptUserConstants.VERSION);
        MongoUsers users = mongoUsersService.save(mongoUsers);

        // 查出 root 的 teamId
//        MongoUsers root = Optional.ofNullable(mongoUsersService.findByUsername(knowledgeProperties.getRootName())).orElse(new MongoUsers());
//        MongoTeamMembers rootTeamMember = Optional.ofNullable(mongoTeamMembersService.findByUserId(root.getId())).orElse(new MongoTeamMembers());

        MongoTeams teams = new MongoTeams();
        teams.setName(dept.getDeptId()+"-"+dept.getDeptName());
        teams.setCreateTime(DateUtils.getNowDate());
        teams.setVersion(FastGptUserConstants.VERSION);


        teams.setPath("");
        teams.setPathId("twoFcjKLaZu6");

        teams.setTeamId(users.getId());
        teams.setOwnerId(String.valueOf(users.getId()));
        teams.setUpdateTime(new Date());
        teams.setCreateAt(new Date());
        teams.setDefaultPermission("0");
        teams.setAvatar("/icon/logo.svg");
        MongoTeams mongoTeams = mongoTeamsService.save(teams);

        // 将新建的用户加入 admin 团队下
        MongoTeamMembers teamMembers = new MongoTeamMembers();
        teamMembers.setAvatar("/imgs/avatar/GrayModernAvatar.svg");
        teamMembers.setTeamId(mongoTeams.getId());
        teamMembers.setUserId(users.getId());

        teamMembers.setName(FastGptUserConstants.TEAM_MEMBER_NAME);
        teamMembers.setRole(FastGptUserConstants.TEAM_MEMBER_NAME_NEW);
        teamMembers.setStatus(FastGptUserConstants.USER_STATUS);
//        teamMembers.setCreateTime(DateUtils.getNowDate());
        teamMembers.setDefaultTeam(true);
        //新增

        teamMembers.setUpdateTime(new Date());
        teamMembers.setCreateAt(new Date());

        mongoTeamMembersService.save(teamMembers);


    }


    /**
     * 修改保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override

    public int updateDept(SysDept dept)
    {
//        SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId());
//        SysDept oldDept = deptMapper.selectDeptById(dept.getDeptId());
//        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept))
//        {
//            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
//            String oldAncestors = oldDept.getAncestors();
//            dept.setAncestors(newAncestors);
//            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
//        }
        //要修改客服部门时，判断是否可以修改客服部门


        int result = deptMapper.updateDept(dept);
//        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()) && StringUtils.isNotEmpty(dept.getAncestors())
//                && !StringUtils.equals("0", dept.getAncestors()))
//        {
//            // 如果该部门是启用状态，则启用该部门的所有上级部门
//            updateParentDeptStatusNormal(dept);
//        }

        // 构建部门与 openapi 的绑定
     //   buildDeptBindOpenapi(dept);

        buildDeptBindShareIdUsers(dept);
        return result;
    }

    private void buildDeptBindOpenapi(SysDept sysDept) {

        FastGptOpenapiVo fastGptOpenapiVo = sysDept.getFastGptOpenapiVo();
        if(ObjectUtil.isEmpty(fastGptOpenapiVo)){
            return;
        }
        String openapi = String.valueOf(fastGptOpenapiVo.getId());

        // 删除原本的绑定关系
        sysDeptOpenapiMapper.deleteSysDeptOpenapiByDeptId(sysDept.getDeptId());
        // 构建新的关系
        SysDeptOpenapi deptOpenapi = SysDeptOpenapi.builder().deptId(sysDept.getDeptId()).openapiId(openapi).build();
        sysDeptOpenapiMapper.insertSysDeptOpenapi(deptOpenapi);
    }

  //绑定用户和应用流程
  private void buildDeptBindShareIdUsers(SysDept sysDept) {
      try {
          FastGptShareidVo fastGptShareidVo = sysDept.getFastGptShareidVo();
          if (ObjectUtil.isEmpty(fastGptShareidVo)) {
              return;
          }

          String shareid = String.valueOf(fastGptShareidVo.getShareId());
          // 通过 shareId 查询链接表
          MongoOutlinks adminshareIdById = mongoOutlinksService.findShareIdById(shareid);
          if (adminshareIdById == null) {
              throw new IllegalArgumentException("分享ID对应的链接信息不存在");
          }

          // 通过链接表的 appId 查询 app 流程
          MongoApps mongoApps = mongoAppsRepository.findById(adminshareIdById.getAppId());
          if (mongoApps == null) {
              throw new IllegalArgumentException("应用流程未找到");
          }
          mongoApps.setId(null); // 清除原有ID

          // 查询该组织下所有用户
          List<SysUser> sysUsers = userService.selectUserListByDeptId(sysDept.getDeptId());
          if (sysUsers.isEmpty()) {
              //  log.warn("组织 {} 下没有用户，跳过分享ID构建", sysDept.getDeptId());
              System.out.println("下没有用户，跳过分享ID构建");
              return;
          }

          // Step1：构造 username 列表
          List<String> usernameList = sysUsers.stream()
                  .map(u -> u.getUserId() + DeptConstants.DEPT_UNIQUE_SUFFIX_STR)
                  .collect(Collectors.toList());

          // Step2：批量查询
          List<MongoUsers> mongoUsersList = mongoUsersService.findByUsernameList(usernameList);
          if (mongoUsersList.isEmpty()) {
              throw new IllegalArgumentException("未找到与用户对应的 Mongo 数据");
          }

          // Step3：转成 Map，方便后续快速查找
          Map<String, MongoUsers> userIdToMongoUsers = new HashMap<>();
          for (MongoUsers mu : mongoUsersList) {
              String userId = mu.getUsername().replace(DeptConstants.DEPT_UNIQUE_SUFFIX_STR, "");
              userIdToMongoUsers.put(userId, mu);
          }

          // 查询 MongoTeamMembers
          List<ObjectId> mongoUserIds = mongoUsersList.stream()
                  .map(MongoUsers::getId)
                  .collect(Collectors.toList());

          List<MongoTeamMembers> teamMembersList = mongoTeamMembersService.findByUserIdList(mongoUserIds);
          if (teamMembersList.isEmpty()) {
              throw new IllegalArgumentException("未找到 Mongo 团队成员数据");
          }

          Map<String, MongoTeamMembers> mongoUserIdToTeamMember = teamMembersList.stream()
                  .collect(Collectors.toMap(
                          tm -> tm.getUserId().toString(), // 将 ObjectId 转换为 String
                          Function.identity()
                  ));


          Map<Long, MongoTeamMembers> userIdToTeamMembers = new HashMap<>();
          for (SysUser sysUser : sysUsers) {
              MongoUsers mu = userIdToMongoUsers.get(sysUser.getUserId().toString());
              if (mu != null) {
                  // 查找与 sysUser 对应的 MongoTeamMembers，注意将 mu.getId() 转换为 String
                  MongoTeamMembers tm = mongoUserIdToTeamMember.get(mu.getId().toString());
                  if (tm != null) {
                      userIdToTeamMembers.put(sysUser.getUserId(), tm);
                  }
              }
          }

          for (SysUser sysUser : sysUsers) {
              //   MongoUsers users1 = userIdToMongoUsers.get(sysUser.getUserId());
              MongoTeamMembers teamMembers = userIdToTeamMembers.get(sysUser.getUserId());
              if (teamMembers == null) {
                  continue; // 如果没有对应的团队成员，跳过
              }
              String  userShareId=shareIdprefix+sysUser.getUserId()+shareIdsuffix;

              this.processOneUser(
                      sysUser, mongoApps, adminshareIdById, teamMembers, userShareId
              );
//              mongoAppsRepository.deleteByTeamId(teamMembers.getTeamId());
//
//              MongoApps newApp = BeanUtil.copyProperties(mongoApps, MongoApps.class);
//              newApp.setTeamId(teamMembers.getTeamId());
//              newApp.setId(null);
//              mongoAppsRepository.save(newApp);
//             //更新chats表
////              List<MongoChats> mongoChats = mongoChatsService.findByTeamId(teamMembers.getTeamId());
////
////              mongoChats.forEach(chats -> chats.setAppId(newApp.getId()));
////              mongoChatsService.batchInsert(mongoChats);
//              mongoChatsService.updateAppIdByTeamId(teamMembers.getTeamId(),newApp.getId());
//
//              mongoChatitemsService.updateAppIdByTeamId(teamMembers.getTeamId(),newApp.getId());
//
//
//
//              mongoOutlinksService.deleteByTeamId(teamMembers.getTeamId());
//
//              MongoOutlinks mongoOutlinks = new MongoOutlinks();
//              mongoOutlinks.setAppId(newApp.getId());
//              mongoOutlinks.setName(sysUser.getUserId() + "--" + adminshareIdById.getName());
//              mongoOutlinks.setTeamId(teamMembers.getTeamId());
//              mongoOutlinks.setTmbId(teamMembers.getId());
//            //  String random = generateRandomString();
//
//              mongoOutlinks.setType("share");
//              mongoOutlinks.setShareId(shareIdprefix+sysUser.getUserId()+shareIdsuffix);
//              mongoOutlinks.setResponseDetail(true);
//              mongoOutlinks.setShowNodeStatus(true);
//              mongoOutlinks.setShowRawSource(true);
//              mongoOutlinks.setUsagePoints(0);
//
//              MongoOutlinks.Limit limit = new MongoOutlinks.Limit();
//              limit.setMaxUsagePoints(-1);
//              limit.setQPM(100);
//              mongoOutlinks.setLimit(limit);
//
//              mongoOutlinksService.save(mongoOutlinks);
//
//              sysUserShareidService.deleteSysUserShareidByUserId(sysUser.getUserId());
//
//              SysUserShareid userShareid = new SysUserShareid();
//              userShareid.setUserId(sysUser.getUserId());
//              userShareid.setName(sysUser.getUserName());
//              userShareid.setShareid(shareIdprefix+sysUser.getUserId()+shareIdsuffix);
//              sysUserShareidService.insertSysUserShareid(userShareid);
          }

          sysDeptShareidMapper.deleteSysDeptShareidByDeptId(sysDept.getDeptId());

          SysDeptShareid deptShareid = SysDeptShareid.builder()
                  .deptId(sysDept.getDeptId())
                  .shareid(shareid)
                  .name(adminshareIdById.getName())
                  .build();
          sysDeptShareidMapper.insertSysDeptShareid(deptShareid);

      } catch (Exception e) {

          throw new RuntimeException("构建部门绑定分享ID用户失败", e); // 抛出一个运行时异常来回滚事务
      }


  }

    @Transactional(rollbackFor = Exception.class)
    public void processOneUser(SysUser sysUser,
                               MongoApps templateApp,
                               MongoOutlinks templateOutlink,
                               MongoTeamMembers teamMembers,
                               String shareid) {

        // 删除旧 app
        mongoAppsRepository.deleteByTeamId(teamMembers.getTeamId());

        // 复制 app
        MongoApps newApp = BeanUtil.copyProperties(templateApp, MongoApps.class);
        newApp.setTeamId(teamMembers.getTeamId());
        newApp.setId(null);
        mongoAppsRepository.save(newApp);

        // 更新 appId 到 chat/chatitem
        mongoChatsService.updateAppIdByTeamId(teamMembers.getTeamId(), newApp.getId());
        mongoChatitemsService.updateAppIdByTeamId(teamMembers.getTeamId(), newApp.getId());

        // 删除旧 outlink
        mongoOutlinksService.deleteByTeamId(teamMembers.getTeamId());

        // 插入新 outlink
        MongoOutlinks newOutlink = BeanUtil.copyProperties(templateOutlink, MongoOutlinks.class);
        newOutlink.set_id(null);
        newOutlink.setAppId(newApp.getId());
        newOutlink.setTeamId(teamMembers.getTeamId());
        newOutlink.setTmbId(teamMembers.getId());
        newOutlink.setName(sysUser.getUserId() + "--" + templateOutlink.getName());
        newOutlink.setShareId(shareid);
        MongoOutlinks.Limit limit = new MongoOutlinks.Limit();
        limit.setMaxUsagePoints(-1);
        limit.setQPM(100);
        newOutlink.setLimit(limit);
        mongoOutlinksService.save(newOutlink);
//              mongoOutlinksService.deleteByTeamId(teamMembers.getTeamId());
//
//              MongoOutlinks mongoOutlinks = new MongoOutlinks();
//              mongoOutlinks.setAppId(newApp.getId());
//              mongoOutlinks.setName(sysUser.getUserId() + "--" + adminshareIdById.getName());
//              mongoOutlinks.setTeamId(teamMembers.getTeamId());
//              mongoOutlinks.setTmbId(teamMembers.getId());
//            //  String random = generateRandomString();
//
//              mongoOutlinks.setType("share");
//              mongoOutlinks.setShareId(shareIdprefix+sysUser.getUserId()+shareIdsuffix);
//              mongoOutlinks.setResponseDetail(true);
//              mongoOutlinks.setShowNodeStatus(true);
//              mongoOutlinks.setShowRawSource(true);
//              mongoOutlinks.setUsagePoints(0);
//
//              MongoOutlinks.Limit limit = new MongoOutlinks.Limit();
//              limit.setMaxUsagePoints(-1);
//              limit.setQPM(100);
//              mongoOutlinks.setLimit(limit);
//
//              mongoOutlinksService.save(mongoOutlinks);
        // 删除旧 SQL 绑定
        sysUserShareidService.deleteSysUserShareidByUserId(sysUser.getUserId());

        // 插入新 SQL 绑定
        SysUserShareid userShareid = new SysUserShareid();
        userShareid.setUserId(sysUser.getUserId());
        userShareid.setName(sysUser.getUserName());
        userShareid.setShareid(shareid);
        sysUserShareidService.insertSysUserShareid(userShareid);
    }



    private void buildDeptBindShareId(SysDept sysDept) {

        FastGptShareidVo fastGptShareidVo = sysDept.getFastGptShareidVo();
        if(ObjectUtil.isEmpty(fastGptShareidVo)){
            return;
        }
        String shareid = String.valueOf(fastGptShareidVo.getShareId());

        // 删除原本的绑定关系
        sysDeptShareidMapper.deleteSysDeptShareidByDeptId(sysDept.getDeptId());
        // 构建新的关系
        SysDeptShareid deptShareid = SysDeptShareid.builder().deptId(sysDept.getDeptId()).shareid(shareid).build();

        MongoOutlinks shareIdhhhh= mongoOutlinksService.findShareIdById(deptShareid.getShareid());

        if (shareIdhhhh!=null){
            deptShareid.setName(shareIdhhhh.getName());
        }


        sysDeptShareidMapper.insertSysDeptShareid(deptShareid);
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatusNormal(SysDept dept)
    {
        String ancestors = dept.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        deptMapper.updateDeptStatusNormal(deptIds);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors)
    {
        List<SysDept> children = deptMapper.selectChildrenDeptById(deptId);
        for (SysDept child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            deptMapper.updateDeptChildren(children);
        }
    }

    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public int deleteDeptById(Long deptId)
    {
        delFastGptUser(deptId);
        return deptMapper.deleteDeptById(deptId);
    }

    @Override
    public Long findRootTreeId(Long parentId) {
        List<SysDept> sysDepts = deptMapper.selectParentId(parentId);
        if (sysDepts==null||sysDepts.size()==0){
            return 0L;
        }
        SysDept dept = sysDepts.get(0);
        if (dept.getParentId()==0L){
            return dept.getDeptId();
        }
        return findRootTreeId(dept.getParentId());
    }

    /**
     * 判断用户的组织是否是管理员和一级组织
     * @param deptId
     * @return
     */
    @Override
    public boolean selectJudgeMenusRole(Long deptId) {
        SysDept sysDept = deptMapper.selectJudgeDeptById(deptId);

        if (sysDept==null){
            return false;
        }
        return true;
    }

    @Override
    public SysDept findByDeptName(String className) {
        SysDept dept = deptMapper.findByDeptName(className);

        return dept;
    }


    /**
     * 删除部门与fastGpt的联系
     */
    private void delFastGptUser(Long deptId) {
        SysDept sysDept = deptMapper.selectDeptById(deptId);

        // 如果不是 DEPT_UNION_FAST_GPT_DEEP 层级则无绑定关系，不需要处理
        String ancestors = sysDept.getAncestors();
        List<String> splitByComma = StrUtil.split(ancestors, ",");
        if(ObjectUtil.isNotNull(splitByComma) && splitByComma.size() != DeptConstants.DEPT_UNION_FAST_GPT_DEEP){
            return;
        }

        MongoUsers mongoUsers = Optional.ofNullable(mongoUsersService.findByUsername(deptId + DeptConstants.DEPT_UNIQUE_SUFFIX_STR)).orElse(new MongoUsers());
        MongoTeamMembers teamMembers = Optional.ofNullable(mongoTeamMembersService.findByUserId(mongoUsers.getId())).orElse(new MongoTeamMembers());
        if(ObjectUtil.isNotNull(teamMembers.getId())){
            mongoTeamMembersService.deleteById(teamMembers.getId());
        }
        if(ObjectUtil.isNotNull(mongoUsers.getId())){
            mongoUsersService.deleteById(mongoUsers.getId());
        }
    }


    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t)
    {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t)
    {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext())
        {
            SysDept n = (SysDept) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t)
    {
        return getChildList(list, t).size() > 0;
    }
}
